#!/usr/bin/env python

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from FrameSSHBase import Ui_FrameSSH

class FrameSSH(Ui_FrameSSH, QFrame):
    def __init__(self, connection, parent = None) :
        super(FrameSSH, self).__init__(parent)

        self.setupUi(self)
        self.SSH = connection.root.Servers.SSH.SSH()

        self.supportedOptions = ['PasswordAuthentication', 'PermitEmptyPasswords', \
                                'PermitRootLogin', 'PubkeyAuthentication', \
                                'PrintMotd', 'UsePAM', 'ListenAddress', 'Port', \
                                'Protocol', 'X11Forwarding', 'SyslogFacility' ]

        self.defaultOptions = {'PasswordAuthentication' : 'yes', \
                               'PermitEmptyPasswords' : 'no', \
                               'PermitRootLogin' : 'yes', \
                               'PubkeyAuthentication' : 'yes', \
                               'PrintMotd' : 'yes', 'UsePAM' : 'no', \
                               'ListenAddress' : '0.0.0.0', \
                               'Port' : '22', 'Protocol' : '2,1', \
                               'X11Forwarding' : 'no', \
                               'SyslogFacility' : 'AUTH'}

        self.radioOptions = ['PasswordAuthentication', 'PermitEmptyPasswords', \
                              'PermitRootLogin', \
                              'PubkeyAuthentication', 'PrintMotd', \
                              'UsePAM', 'X11Forwarding' ]

        self.syslogFacilities = ['AUTH', 'AUTHPRIV', 'DAEMON', 'USER', \
                                'LOCAL0', 'LOCAL1', 'LOCAL2', 'LOCAL3', \
                                'LOCAL4', 'LOCAL5', 'LOCAL6', 'LOCAL7']

        self.loadConfiguration()


    def loadConfiguration(self):

        self.currentOptions = self.SSH.getOptions()

        for key, value in self.currentOptions.iteritems() :
            if key in self.radioOptions :
                if value == 'yes' :
                    exec('self.rdio' + key + 'Yes.setChecked(True)')
                elif value == 'no' :
                    exec('self.rdio' + key + 'No.setChecked(True)')
            else :
                self.setSpecialOption(key, value)

        currentKeys = self.currentOptions.keys()

        for key, value in self.defaultOptions.iteritems() :
            if currentKeys.count(key) == 0 :
                if key in self.radioOptions :
                    if value == 'yes' :
                        exec('self.rdio' + key + 'Yes.setChecked(True)')
                    elif value == 'no' :
                        exec('self.rdio' + key + 'No.setChecked(True)')
                else :
                    self.setSpecialOption(key, value)


    def loadDefaultConfiguration(self):
        for key, value in self.defaultOptions.iteritems() :
            if key in self.radioOptions :
                if value == 'yes' :
                    exec('self.rdio' + key + 'Yes.setChecked(True)')
                elif value == 'no' :
                    exec('self.rdio' + key + 'No.setChecked(True)')
            else :
                self.setSpecialOption(key, value)


    def setSpecialOption(self, key, value):
        if key == 'ListenAddress' :
            self.txtListenAddress.setText(value)

        elif key == 'Port' :
            self.txtPort.setText(value)

        elif key == 'Protocol' :
            if value == '1' :
                self.chkProtocolV1.setChecked(True)
                self.chkProtocolV2.setChecked(False)
            elif value == '2' :
                self.chkProtocolV1.setChecked(False)
                self.chkProtocolV2.setChecked(True)
            elif value == '1,2' or value == '2,1' :
                self.chkProtocolV1.setChecked(True)
                self.chkProtocolV2.setChecked(True)

        elif key == 'SyslogFacility' :
            currentIndex = self.syslogFacilities.index(value)
            self.cmbSyslogFacility.setCurrentIndex(currentIndex)


    def getSpecialOption(self, option):
        value = False
        if option == 'ListenAddress' :
            value = str(self.txtListenAddress.text())

        elif option == 'Port' :
            value = str(self.txtPort.text())

        elif option == 'SyslogFacility' :
            currentIndex = self.cmbSyslogFacility.currentIndex()
            value = self.syslogFacilities[currentIndex]

        elif option == 'Protocol' :
            if self.chkProtocolV1.isChecked() and not self.chkProtocolV2.isChecked() :
                value = '1'

            elif self.chkProtocolV2.isChecked() and not self.chkProtocolV1.isChecked() :
                value = '2'

            elif self.chkProtocolV1.isChecked() and self.chkProtocolV2.isChecked() :
                value = '2,1'

        if value :
            return value
        else :
            raise TypeError, option + ' is not valid!'


    def saveConfiguration(self):
        if not self.chkProtocolV1.isChecked() and not self.chkProtocolV2.isChecked() :
            QMessageBox.critical(self, "Error!", "Please select at least one protocol.")
            return

        newConfiguration = {}

        for option in self.supportedOptions :
            if option in self.radioOptions :
                if eval('self.rdio' + option + 'Yes').isChecked() :
                    newConfiguration[option] = 'yes'
                elif eval('self.rdio' + option + 'No').isChecked() :
                    newConfiguration[option] = 'no'
            else :
                value = self.getSpecialOption(option)
                newConfiguration[option] = value

        if not self.SSH.saveOptions(newConfiguration) :
            QMessageBox.critical(self, "Error!", "Failed to save the new configuration.")

    ###################################################################
    #                                                                 #
    #                   Connecting Signals to Slots                   #
    #                                                                 #
    ###################################################################



    @pyqtSlot()
    def on_btnReload_clicked(self):
        self.loadConfiguration()

    @pyqtSlot()
    def on_btnLoadDefault_clicked(self):
        self.loadDefaultConfiguration()

    @pyqtSlot()
    def on_btnSave_clicked(self):
        self.saveConfiguration()


